'use strict'
const path = require('path')
const webpack = require('webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const fs = require('fs');
function resolve(dir) {
    return path.join(__dirname, '..', dir)
}
deleteFolder(path.join(__dirname, "../docDist"));
function deleteFolder(path) {
    let files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach(function (file, index) {
            let curPath = path + "/" + file;
            if (fs.statSync(curPath).isDirectory()) {
                deleteFolder(curPath);
            } else {
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};
var data = JSON.parse(fs.readFileSync(path.join(__dirname, './versionCache.json')).toString());
var version = data.version.split('.');
version[3] = parseInt(version[3]);
version[3]++;
if (version[3] < 10) {
    version[3] = '00' + version[3]
} else if (version[3] < 100) {
    version[3] = '0' + version[3]
};
version = version.join('.');
var _json = fs.openSync(path.join(__dirname, './versionCache.json'), 'w');
fs.writeFileSync(_json, JSON.stringify({
    "version": version
}));
const webpackConfig = {
    entry: {
        app: './src/main.js'
    },
    resolve: {
        alias: {
            '@': resolve('src'),
        },
    },
    module: {
        rules: [{
            test: /\.js$/,
            loader: 'babel-loader',
            include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
        }, {
            test: /\.css$/,
            use: ['style-loader', 'css-loader']
        }, {
            test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
            loader: 'url-loader',
        }, {
            test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
            loader: 'url-loader',

        }, {
            test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
            loader: 'url-loader',
        }, {
            test: /\.(html)$/,
            use: {
                loader: 'html-loader',
                options: {}
            }
        }]
    },
    devtool: false,
    output: {
        path: path.resolve(__dirname, '../dist'),
        filename: '[name].js?' + data.version,
        publicPath: './'
    },
    plugins: [
        new webpack.BannerPlugin('当前版本 ： ' + version + '\n'),
        new webpack.DefinePlugin({
            'process.env': '"production"'
        }),
        new UglifyJsPlugin({
            uglifyOptions: {
                compress: {
                    warnings: false,
                    pure_funcs: ['console.log'],
                }
            },
            sourceMap: true,
            parallel: true
        }),
        new ExtractTextPlugin({
            filename: path.posix.join('static', 'css/[name].[contenthash].css'),
            allChunks: true,
        }),
        new OptimizeCSSPlugin({
            cssProcessorOptions: {
                safe: true,
                map: { inline: false }
            }
        }),
        new HtmlWebpackPlugin({
            filename: path.resolve(__dirname, '../dist/index.html'),
            template: 'index.html',
            inject: true,
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true
            },
            chunksSortMode: 'dependency'
        }),
        new webpack.HashedModuleIdsPlugin(),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks(module) {
                return (
                    module.resource &&
                    /\.js$/.test(module.resource) &&
                    module.resource.indexOf(
                        path.join(__dirname, '../node_modules')
                    ) === 0
                )
            }
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'manifest',
            minChunks: Infinity
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'app',
            async: 'vendor-async',
            children: true,
            minChunks: 3
        }),
        new CopyWebpackPlugin([{
            from: path.resolve(__dirname, '../static'),
            to: 'static',
            ignore: ['.*']
        }, {
            from: path.resolve(__dirname, '../config.js'),
            to: './',
            ignore: ['.*']
        }])
    ]
};
if (process.env.npm_config_report) {
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
    webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig